﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.API.Application.Services;
using Casamiel.Application;
using Casamiel.Common;
using Casamiel.Domain.Entity;
using Casamiel.Domain.Request.IC;
using MediatR;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Casamiel.API.Application.Commands
{
    /// <summary>
    /// Update wx extension command handler.
    /// </summary>
    public sealed class UpdateWxExtensionCommandHandler : IRequestHandler<UpdateWxExtensionCommand, bool>
    {
        /// <summary>
        /// The wx extension service.
        /// </summary>
        private readonly IWxExtensionService _wxExtensionService;
        private readonly IMemberCardService _cardService;
        private readonly CasamielSettings casamielSettings;
        private readonly List<ActivityInfo> _activityInfos;
        private readonly IIcApiService _icApiService;
        private readonly IMemberCouponRecordService _memberCouponRecordService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="wxExtension"></param>
        /// <param name="cardService"></param>
        /// <param name="CasamielSettings"></param>
        /// <param name="optionsSnapshot"></param>
        /// <param name="icApiService"></param>
        /// <param name="memberCouponRecordService"></param>
        public UpdateWxExtensionCommandHandler(IWxExtensionService wxExtension, IMemberCardService cardService, IOptionsSnapshot<CasamielSettings> CasamielSettings,
            IOptionsSnapshot<List<ActivityInfo>> optionsSnapshot, IIcApiService icApiService, IMemberCouponRecordService memberCouponRecordService)
        {
            if (CasamielSettings is null) {
                throw new ArgumentNullException(nameof(CasamielSettings));
            }

            if (optionsSnapshot is null) {
                throw new ArgumentNullException(nameof(optionsSnapshot));
            }

            _wxExtensionService = wxExtension;
            _cardService = cardService;
            casamielSettings = CasamielSettings.Value;
            _activityInfos = optionsSnapshot.Value;
            _icApiService = icApiService;
            _memberCouponRecordService = memberCouponRecordService;
        }

        /// <summary>
        /// Handle the specified request and cancellationToken.
        /// </summary>
        /// <returns>The handle.</returns>
        /// <param name="request">Request.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        public async Task<bool> Handle(UpdateWxExtensionCommand request, CancellationToken cancellationToken)
        {
            if (request == null) {
                throw new ArgumentNullException(nameof(request));
            }

            if (request.WxId > 0) {
                var entity = await _wxExtensionService.FindAsync<ICasaMielSession>(request.WxId).ConfigureAwait(false);
                if (entity != null) {
                    entity.Mobile = request.Mobile;
                    entity.UpdateTime = DateTime.Now;
                    await _wxExtensionService.UpdateAsync<ICasaMielSession>(entity).ConfigureAwait(false);
                }
            }
            if (!string.IsNullOrEmpty(request.CardNO)) {
                var entity = await _wxExtensionService.FindAsync<ICasaMielSession>(request.Mobile).ConfigureAwait(false);
                if (entity != null && entity.Status == 0) {
                    entity.CardNO = request.CardNO;
                    entity.Status = 1;
                    entity.UpdateTime = DateTime.Now;
                    await _wxExtensionService.UpdateAsync<ICasaMielSession>(entity).ConfigureAwait(false);

                    if (casamielSettings.ApiName == "hgspApi") {
                        var activityId = 8;
                        switch (entity.ShopId) {
                            case 456:
                                if (DateTime.Now > DateTime.Parse("2019-12-31 23:59:59")) {
                                    return false;
                                }
                                break;
                            case 87:
                                if (DateTime.Now > DateTime.Parse("2019-12-31 23:59:59")) {
                                    return false;
                                }
                                break;
                            default:
                                return false;
                        }

                        var activityinfo = _activityInfos.Find(c => c.Id == activityId);
                        if (activityinfo == null) {
                            return false;
                        }

                        var coupon = new MemberCouponRecord { CardNO = entity.CardNO, Mobile = request.Mobile, ActivityId = activityId, Status = 1, CreateTime = DateTime.Now };
                        var req = new AddTicketsReq { Cardno = entity.CardNO, Phoneno = request.Mobile };
                        req.Largesstickets = new List<Domain.Request.IC.Ticket>();
                        foreach (var item in activityinfo.Tickets) {
                            req.Largesstickets.Add(new Domain.Request.IC.Ticket { Ticketid = item.TicketId, Ticketnum = item.Count, Ticketprice = item.Price });
                        }

                        var d = await _icApiService.Icticketlargess(req).ConfigureAwait(false);
                        if (d.code == 0) {
                            var jjobj = JsonConvert.DeserializeObject<JObject>(d.content);
                            coupon.Largessno = jjobj["largessno"].ToString();
                            coupon.RequestInfo = JsonConvert.SerializeObject(req);
                            await _memberCouponRecordService.AddAsync<ICasaMielSession>(coupon).ConfigureAwait(false);
                        } else {
                            //if (activityinfo.Total > 0) {
                            //    var myda = new Enyim.Caching.Memcached.CasResult<object>();
                            //    if (_memcachedClient.TryGetWithCas(_cachekey, out myda)) {
                            //        total = (int)myda.Result - 1;
                            //        _memcachedClient.Cas(Enyim.Caching.Memcached.StoreMode.Replace, _cachekey, total);
                            //    }
                            //}
                            coupon.Largessno = d.code.ToString(CultureInfo.CurrentCulture);
                            coupon.RequestInfo = JsonConvert.SerializeObject(req);
                            coupon.Status = -1;
                            await _memberCouponRecordService.AddAsync<ICasaMielSession>(coupon);
                        }

                    }

                }
            }
            return true;
        }
    }
}
